import unittest

from django.test import TestCase
from backend.po.supplier import Supplier
from backend.services import SupplierService, ObjectValidationError


class SupplierSvcTestCast(TestCase):
    def setUp(self):
        self.svc = SupplierService()

    def test_crud(self):
        objs = self.svc.list()
        self.assertEqual(0, len(objs))

        supplier_obj = Supplier(supplier_name='JD',
                                contact_name='LiuQiangdong',
                                contact_no='12812348765')

        self.assertEqual(0, supplier_obj.id)
        supplier_obj = self.svc.create(supplier_obj)
        self.assertNotEqual(0, supplier_obj.id)

        get_supplier_obj = self.svc.retrieve(supplier_obj.id)
        self.assertEqual(supplier_obj.contact_name, get_supplier_obj.contact_name)

        get_supplier_obj.contact_name = 'LQD'
        self.assertTrue(self.svc.update(get_supplier_obj))
        get_supplier_obj = self.svc.retrieve(supplier_obj.id)
        self.assertEqual('LQD', get_supplier_obj.contact_name)

        objs = self.svc.list()
        self.assertEqual(1, len(objs))
        self.assertTrue(self.svc.destroy(objs[0].id))
        objs = self.svc.list()
        self.assertEqual(0, len(objs))

    def test_invalid_length(self):
        supplier = Supplier(supplier_name='PDD',
                            contact_name='HZ',
                            contact_no='123456789012345678901234567890123')

        with self.assertRaises(ObjectValidationError):
            self.svc.create(supplier)


if __name__ == '__main__':
    unittest.main(verbosity=2)
